package homework6.exp3;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test3 {

    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        Document document = documentBuilder.parse("src/phone.xml");
        NodeList brandList = document.getElementsByTagName("Brand");
        for (int i=0;i<brandList.getLength();i++){
            Element brandElement = (Element)brandList.item(i);
            String brandName = brandElement.getAttribute("name");
            if (brandName.equals("MOTO")){
                brandElement.setAttribute("name","摩托罗拉");
            }

            //保存文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(document);

            //设置编码
            transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
            StreamResult result = new StreamResult(new FileOutputStream("src/phone.xml"));
            transformer.transform(domSource,result);
        }
    }
}
